package com.xiezc.dht.service;

import com.xiezc.dht.message.Message;
import com.xiezc.dht.message.MessageBuild;
import com.xiezc.dht.model.BeContent;
import com.xiezc.dht.model.BeMap;
import com.xiezc.dht.util.BeException;
import com.xiezc.dht.util.BecodeUtil;
import com.xiezc.dht.util.Const;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @author wb-xzc291800
 */
@Slf4j
public class UdpService {

    @Getter
    private DatagramSocket socket;

    public UdpService(int port) {
        try {
            socket = new DatagramSocket(port);
            log.info("udp socket在{}端口初始化完成........", port);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BeException(e);
        }
    }

    /**
     * 接收一条消息的业务逻辑
     */
    public Message recevice() throws IOException {
        DatagramPacket datagramPacket = new DatagramPacket(new byte[Const.receviceDataLen], Const.receviceDataLen);
        socket.receive(datagramPacket);
        InetSocketAddress socketAddress = (InetSocketAddress) datagramPacket.getSocketAddress();

        BeMap mapBeObject = (BeMap) BecodeUtil.prase(new BeContent(datagramPacket.getData()));
        Message message = MessageBuild.buildMsg(mapBeObject, socketAddress);
        if (message != null) {
            log.info("recevice   {} -- {} ", message.getMsgTypeEnum(), message.getSocketAddress());
        }
        return message;
    }

    /**
     * 从队列中取出一条消息 发送
     */
    public void sendDate(Message message) throws IOException {
        log.info("sendDate {} -- {} ", message.getMsgTypeEnum(), message.getSocketAddress());
        byte[] bytes = message.getBeMap().getContent();
        InetSocketAddress socketAddress = message.getSocketAddress();
        //log.warn(socketAddress.toString());
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, socketAddress);
        socket.send(datagramPacket);
    }


}